package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import org.example.JavaBean.plus.User;
import org.example.config.JwtConfig;
import org.example.handler.PasswordNotFoundException;
import org.example.handler.UserNameNotFontException;
import org.example.mapper.UserMapper;
import org.example.service.UserService;
import org.example.util.JsonResult;
import org.example.util.MD5Util;
import org.example.util.ResultTool;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Auther:Liu
 * @Testname:UserServiceImpl
 * @Date:2025/8/13 14:55
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public JsonResult login(User user) {
        User checked = checkUsername(user.getUsername());
        if (checked==null){
           throw new UserNameNotFontException("账号不存在");
        }
        if (!checked.getPassword().equals(MD5Util.encryptMD5(user.getPassword()))){
          throw new PasswordNotFoundException("密码错误");
        }
        String jwtToken = JwtConfig.getJwtToken(checked);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set("token:"+checked.getId(),jwtToken);
        return ResultTool.success(jwtToken);
    }

    @Override
    public JsonResult isLogin(String token) {
        boolean b = JwtConfig.checkToken(token);
        if (!b){
            return ResultTool.fail(201,"用户没有登陆");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String s = ops.get("token:" + userId);
        if (s == null){
            return ResultTool.fail(201,"用户没有登陆");
        }
        if (!Objects.equals(s,token)){
            return ResultTool.fail(201,"用户没有登陆");
        }
        return ResultTool.success(claims.get("name"));
    }

    @Override
    public JsonResult Loginout(String token) {
        boolean b = JwtConfig.checkToken(token);
        if (!b){
            return ResultTool.fail(201,"退出失败");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        Boolean deleted = stringRedisTemplate.delete("token:" + userId);
        if (!deleted){
            return ResultTool.fail(201,"退出失败");
        }
        return ResultTool.success("success");
    }


    public User checkUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("username", username);
        return getOne(wrapper);
    }
}
